<template>
  <div class="configuration_container">
    <input
      type="file"
      ref="fileUpload"
      accept="audio/*"
      style="display: none"
      @change="uploadSoundSource"
    />
    <div class="title">通知方式配置</div>
    <div class="group">
      <ul @mousedown.prevent="onMouseDown">
        <li
          :class="{ isactive: type == item.value }"
          :data-id="item.value"
          v-for="(item, index) in alarmMethodsOptions"
          :key="index"
        >
          {{ item.label }}
        </li>
      </ul>
    </div>
    <div class="form_content">
      <div v-if="!loading">
        <div class="Tips">
          {{ tips }}
        </div>
        <BoForm
          ref="formRef"
          :columns="items"
          :show-submit-button="false"
          :label-col="{ style: { width: '145px' } }"
          labelAlign="left"
          :wrapper-col="{ span: 6 }"
          :model="formState"
        >
          <template #shortMessage="{ field }">
            <div class="short_message">
              <FormItemRest>
                <Select
                  v-model:value="formState['shortMessage']"
                  :options="sysCarrierOperatorOptions"
                  style="width: 100px"
                ></Select>
                <Input
                  v-model:value="formState['serviceConfig']"
                  style="width: 78%"
                ></Input>
              </FormItemRest>
            </div>
          </template>
          <template #soundSource="{ field }">
            <div class="flex items-center">
              <Button @click="inputClick">
                <div class="flex items-center justify-center">
                  <UploadOutlined /> 上传
                </div>
              </Button>
              <span style="margin-left: 10px">{{
                formState['soundSource']
              }}</span>
            </div>
          </template>
          <template #footer>
            <!-- <WithPermission code="alarmModeConfig:update"> -->
            <Button
              type="primary"
              class="footer_btn"
              :disabled="isEqualResult"
              @click="submit"
              >提交</Button
            >
            <!-- </WithPermission> -->
          </template>
        </BoForm>
      </div>
      <div v-else class="loading-overlay">
        <Spin></Spin>
      </div>
    </div>
  </div>
</template>
<route lang="json">
{
  "name": "alarm-methods",
  "meta": {
    "title": "通知方式管理"
  }
}
</route>
<script setup lang="tsx">
import { computed, ref, watch } from 'vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { useDicts } from '@boeyo/portal';
import { BoForm, BoFormProps } from '@boeyo/ui';
import {
  Button,
  FormItemRest,
  Input,
  Modal,
  Select,
  Spin,
  message,
} from 'ant-design-vue';
import { cloneDeep, isEqual } from 'lodash-es';
import { onBeforeRouteLeave } from 'vue-router';
import {
  getAlarmModeConfigInfo,
  updateAlarmModeConfigInfo,
  uploadImage,
} from './api';

const dictArr = [
  'sys_alarm_time',
  'sys_carrier_operator',
  'radio_status',
  'alarm_methods',
];

const { sysCarrierOperatorOptions, alarmMethodsOptions, radioStatusOptions } =
  useDicts(dictArr);

const fileUpload = ref();
const inputClick = () => {
  fileUpload.value && fileUpload.value.click();
};
const uploadSoundSource = async (e: any) => {
  const file = e.target.files[0];
  const formData = new FormData();
  formData.append('file', file, file.name);
  formData.append('fileName', file.name);
  const res = await uploadImage(formData);
  message.success('上传成功');
  formRef.value.setFiledValue('soundSource', res.data.filePath);
  e.target.value = '';
};

const type = ref('1');
const loading = ref(false);
const formState = ref({});
const contrastObj = ref({});
const isEqualResult = computed(() => {
  return isEqual(formState.value, contrastObj.value);
});

const tips = computed(() => {
  switch (type.value) {
    case '1':
      return '使用web端登录的硬件音频设备进行警报提示，以下为警报配置项。在告警推送配置中勾选此配置方式才可生效。';
    case '2':
      return '当系统产生告警时，将置顶显示此消息弹窗。在告警推送配置中勾选此推送方式才可生效使用。';
    case '3':
      return '当系统产生告警时，将通过短信的方式将告警信息发送给通知对象。在告警推送配置中勾选此推送方式才可生效使用。系统用户信息中需要已经配置电话号码信息。';
    case '4':
      return '当系统产生告警时，将通过企业微信将告警信息发送给通知对象。在告警推送配置中勾选此推送方式才可生效使用。系统用户信息中需要已经进行企业微信认证。';
    case '5':
    case '6':
      return '当系统产生告警时，将通过微信公众号将告警信息发送给通知对象。在告警推送配置中勾选此推送方式才可生效使用。需用户使用公众号进行角色绑定登录。';
    default:
      return '';
  }
});

const showWichContent = () => {
  switch (type.value) {
    case '1':
      return '播报内容';
    case '2':
      return '显示内容';
    default:
      return '模板内容';
  }
};

// const showWichTime = () => {
//   switch (type.value) {
//     case '1':
//       return '警报时长';
//     case '2':
//       return '弹窗停留时长';
//   }
// };

const items = computed<BoFormProps['columns']>(() => {
  return [
    {
      title: '是否开启',
      valueType: 'radio',
      dataIndex: 'enable',
      fieldProps: {
        options: radioStatusOptions.value,
      },
    },
    // {
    //   label: showWichTime(),
    //   valueType: 'select',
    //   dataIndex: 'warningDuration',
    //   fieldProps: {
    //     options: sysAlarmTimeOptions.value,
    //   },
    //   hidden: () => type.value !== '1' && type.value !== '2',
    // },
    // {
    //   title: '音源服务',
    //   valueType: 'input',
    //   dataIndex: 'soundSource',
    //   hidden: () => type.value !== '1',
    // },
    {
      label: showWichContent(),
      valueType: 'checkboxGroup',
      dataIndex: 'broadcastContent',
      fieldProps: {
        options: [
          { label: '标题', value: '1' },
          { label: '告警时间', value: '2' },
          { label: '告警内容', value: '3' },
          // { label: '告警阈值', value: '4' },
          // { label: '当前值', value: '5' },
        ],
      },
    },
    {
      title: '示例',
      dataIndex: 'noticeExample',
      valueType: 'textarea',
      fieldProps: {
        rows: 8,
      },
    },
    {
      title: '',
      dataIndex: 'footer',
      valueType: 'input',
    },
  ] as BoFormProps['columns'];
});

const getAlarmInfo = async () => {
  loading.value = true;
  const { data } = await getAlarmModeConfigInfo({ type: type.value });
  loading.value = false;
  formState.value = conversionFn(data, 'totiledToArr');
  contrastObj.value = cloneDeep(formState.value);
  formRef.value && formRef.value.setFieldsValue(formState.value);
};

const conversionFn = (data: any, way: string) => {
  const obj = cloneDeep(data);
  if (way === 'totiledToArr') {
    obj.broadcastContent = [];
    if (obj.showTitle === '1') obj.broadcastContent.push('1');
    if (obj.showAlarmTime === '1') obj.broadcastContent.push('2');
    if (obj.showAlarmContent === '1') obj.broadcastContent.push('3');
    // if (obj.showThreshold === '1') obj.broadcastContent.push('4');
    // if (obj.showCurrentValue === '1') obj.broadcastContent.push('5');
  } else {
    obj.showTitle = obj.broadcastContent?.includes('1') ? '1' : '0';
    obj.showAlarmTime = obj.broadcastContent?.includes('2') ? '1' : '0';
    obj.showAlarmContent = obj.broadcastContent?.includes('3') ? '1' : '0';
    // obj.showThreshold = obj.broadcastContent?.includes('4') ? '1' : '0';
    // obj.showCurrentValue = obj.broadcastContent?.includes('5') ? '1' : '0';
  }
  return obj;
};
//修改后提交
const submit = async () => {
  const queryParams = conversionFn(formState.value, 'arrToTotiled');
  console.log(queryParams, 'queryParams');

  const relust: any = await updateAlarmModeConfigInfo(queryParams);
  if (relust.code === 200) {
    message.success(relust.msg);
    contrastObj.value = cloneDeep(formState.value);
  } else {
    message.info(relust.msg);
    setTimeout(() => {
      getAlarmInfo();
    }, 1000);
  }
};

watch(
  () => type.value,
  () => {
    getAlarmInfo();
  },
  { deep: true, immediate: true },
);
const formRef = ref();
const onMouseDown = (e: any) => {
  if (e.target.tagName !== 'LI') return;
  const current = e.target.dataset.id;
  // if (isEqualResult.value || !hasPermission('alarmModeConfig:update'))
  if (isEqualResult.value) return (type.value = current);
  Modal.confirm({
    title: '系统提示',
    content: `当前修改还未保存,确定离开吗?`,
    onOk: async () => {
      type.value = current;
    },
  });
};
onBeforeRouteLeave((to, form, next) => {
  // if (isEqualResult.value || !hasPermission('alarmModeConfig:update')) {
  if (isEqualResult.value) {
    next();
  } else {
    Modal.confirm({
      title: '系统提示',
      content: `当前修改还未保存,确定离开吗?`,
      onOk: async () => {
        next();
      },
    });
  }
});
</script>
<style scoped lang="scss">
.configuration_container {
  padding: 15px;

  .title {
    font-size: 18px;
    font-weight: 700;
  }

  .group {
    :deep(.ant-radio-group) {
      padding: 20px;

      .ant-radio-button-wrapper {
        min-width: 150px;
        height: 40px;
        line-height: 40px;
        text-align: center;

        &-checked:hover {
          background: #1890ff;
        }
      }
    }

    ul {
      display: flex;
      padding: 20px;

      li {
        cursor: pointer;
        padding: 10px 0;
        border: 0.5px solid #ccc;
        min-width: 150px;
        text-align: center;

        &.isactive {
          color: #fff;
          background: #1677ff;
          border-color: transparent;

          &:hover {
            background: #1890ff;
            border: 0.5px solid #fff;
          }
        }

        &:first-child {
          border-radius: 3px 0 0 3px;
        }

        &:nth-child(n + 2) {
          border-left: none;
        }

        &:last-child {
          border-radius: 0 3px 3px 0;
        }
      }
    }
  }

  .form_content {
    position: relative;
    padding: 0 20px;

    .loading-overlay {
      position: absolute;
      top: 150px;
      left: 350px;
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 1000;
      /* 确保遮罩层在最上层 */
    }
  }

  .Tips {
    padding: 3px 8px;
    margin-bottom: 10px;
    font-size: 12px;
    color: #1890ff;
    background: #ecf6ff;
    border: 1px solid #a6cfff;
    border-radius: 3px;
  }

  .short_message {
    display: flex;
    justify-content: space-between;
  }

  :deep(.ant-space-align-center) {
    .ant-space-item:first-child {
      display: none;
    }
  }

  .footer_btn {
    margin-left: 145px;
  }
}
</style>
